//
//  EventDetailViewController.m
//  lvtu
//
//  Created by Apple on 12-5-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "EventDetailViewController.h"
#import "EGOImageView.h"
#import "mapViewController.h"
#import "EventEditViewController.h"

@implementation EventDetailViewController
@synthesize placeDetailInfo;
@synthesize isEdit;
@synthesize delegate;
@synthesize isTripExistEvent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithPlaceInfo:(PlaceInfo*)info
{
    self = [super init];
    if (self) {
        // Custom initialization
        placeInfo = info;
        [placeInfo retain];
        isEdit = YES;
        isTripExistEvent = NO;
    }
    return self;
}

- (void)dealloc
{
    delegate = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"添加事件";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"事件详情"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, 51, 30);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(findOutButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* findoutButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    //signupButton.image = [UIImage imageNamed:@"btn_finish_normal.png"];
    self.navigationItem.leftBarButtonItem = findoutButtonItem;
    [findoutButtonItem release];
    
    
    if (isEdit == YES) {
        UIImage* addImage = [UIImage imageNamed:@"ButtonAdd_normal.png"];
        addbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        addbutton.frame = CGRectMake(0, 0, 30, 30);
        [addbutton setBackgroundImage:addImage forState:UIControlStateNormal];
        [addbutton setBackgroundImage:[UIImage imageNamed:@"ButtonAdd_pressed.png"] forState:UIControlStateHighlighted];
        [addbutton addTarget:self action:@selector(addButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImage* delImage = [UIImage imageNamed:@"ButtonDel_normal.png"];
        delbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        delbutton.frame = CGRectMake(29, 0, 30, 30);
        [delbutton setBackgroundImage:delImage forState:UIControlStateNormal];
        [delbutton setBackgroundImage:[UIImage imageNamed:@"ButtonDel_pressed.png"] forState:UIControlStateHighlighted];
        [delbutton addTarget:self action:@selector(delButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        
        UIView* buttonItemView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        [buttonItemView addSubview:addbutton];
        [buttonItemView addSubview:delbutton];
        
        if (isTripExistEvent) {
            [addbutton setEnabled:NO];
            [delbutton setEnabled:YES];
        }
        else
        {
            [addbutton setEnabled:YES];
            [delbutton setEnabled:NO];
        }
        
        UIBarButtonItem* ButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonItemView];
        self.navigationItem.rightBarButtonItem = ButtonItem;
        [ButtonItem release];
        [buttonItemView release];
    }
    
    m_ShowAry = [[NSMutableArray alloc] init];
    
    if (self.view.frame.size.height > 480)
    {
        m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 15, 290, 460) style:UITableViewStylePlain];
    }
    else
    {
        m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 15, 290, 380) style:UITableViewStylePlain];
    }
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    
    UIImageView* inputView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, m_tableView.backgroundView.frame.size.width, m_tableView.backgroundView.frame.size.height)];
    UIImage* stretchImg = [[UIImage imageNamed:@"bg_whiteframe.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    inputView.image = stretchImg;  
    inputView.clipsToBounds = YES;
    inputView.userInteractionEnabled = YES;
    [m_tableView.backgroundView addSubview:inputView];
    
    nodataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    nodataLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2-50);
    nodataLabel.text = @"无数据";
    nodataLabel.backgroundColor = [UIColor clearColor];
    nodataLabel.hidden = YES;
    [self.view addSubview:nodataLabel];
    
    if ([placeInfo isKindOfClass:[PlaceDetailInfo class]]) {
        placeDetailInfo = (PlaceDetailInfo*)placeInfo;
        
        [self.view addSubview:m_tableView];
        [m_tableView reloadData];
    }
    else
    {
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:placeInfo.shopid/*@"123456"*/,@"c_shop_id",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = SHOPDETAIL;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_shop_detail" postInfo:info userInfo:msg];
        
        baseAlert = [[UIAlertView alloc] initWithTitle:@"正在加载..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [baseAlert show];
        
        UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
        [aiv startAnimating];
        [baseAlert addSubview:aiv];
        [aiv release];
    }
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)findOutButtonPressed:(id)sender
{
    BOOL isPop = NO;
//    NSArray* viewControllerArray = [self.navigationController viewControllers];
//    for (UIViewController* viewController in viewControllerArray) {
//        if ([viewController isKindOfClass:[EventEditViewController class]]) {
//            [self.navigationController popToViewController:viewController animated:YES];
//            isPop = YES;
//            break;
//        }
//    }
    if (isPop == NO) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)timerFireMethod:(NSTimer*)theTimer
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    
    [promptAlert release];
    promptAlert =NULL;
}

- (void)addButtonPress:(id)sender
{
    if ([delegate addEvent:placeInfo type:[placeInfo.typeid intValue]]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功！" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        
        [NSTimer scheduledTimerWithTimeInterval:0.5f
                                         target:self
                                       selector:@selector(timerFireMethod:)
                                       userInfo:alert
                                        repeats:NO];
        [alert show];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经添加过啦~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
    [addbutton setEnabled:NO];
    [delbutton setEnabled:YES];
}

- (void)delButtonPress:(id)sender
{
    if ([delegate delEvent:placeInfo type:[placeInfo.typeid intValue]]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"删除成功！" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [NSTimer scheduledTimerWithTimeInterval:0.5f
                                         target:self
                                       selector:@selector(timerFireMethod:)
                                       userInfo:alert
                                        repeats:NO];
        [alert show];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"还未添加呢~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
    [addbutton setEnabled:YES];
    [delbutton setEnabled:NO];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSInteger count = 0;
    switch (section) {
        case 0:
            count = 3;
            break;
        case 1:
            count = 1;
            break;
        case 2:
            count = 1;
            break;    
            
        default:
            break;
    }
    return count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString* string = [[[NSString alloc] init] autorelease];
    switch (section) {
        case 0:
            break;
        case 1:
            string = @"简介";
            break;
        case 2:
            string = @"点评";
            break;    
            
        default:
            break;
    }
    return string;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"StatusCell";
    
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                EGOImageView* cellProfilePic = [[EGOImageView alloc] initWithFrame:CGRectMake(5, 5, 100, 85)];
                cellProfilePic.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f];
                [cell addSubview:cellProfilePic];
                [cellProfilePic release];
                
                UILabel* cellText = [[UILabel alloc]initWithFrame:CGRectMake(120, 20, 160, 30)];
                cellText.backgroundColor = [UIColor clearColor];
                cellText.numberOfLines = 1;
                cellText.font = [UIFont systemFontOfSize:16.0f];
                [cell addSubview:cellText];
                [cellText release];
                
                [cellProfilePic setImageURL:[NSURL URLWithString:placeInfo.imageurl]];
                cellText.text = [NSString stringWithFormat:@"%@",placeInfo.name];
                
                for (int i = 0; i<5; i++) {
                    UIImageView* starImageView = [[UIImageView alloc] initWithFrame:CGRectMake(120+i*24, 55, 24, 24)];
                    starImageView.image = [UIImage imageNamed:@"icn_rate_01.png"];
                    [cell addSubview:starImageView];
                    [starImageView release];
                }
            }
            else if (indexPath.row == 1)
            {
                UIImageView* locationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 8, 34, 34)];
                locationImageView.image = [UIImage imageNamed:@"icn_location.png"];
                [cell addSubview:locationImageView];
                [locationImageView release];
                
                int tempHeight = [placeDetailInfo.adress sizeWithFont:[UIFont systemFontOfSize:18.0f]
                                                    constrainedToSize:CGSizeMake(200, 9999) lineBreakMode:UILineBreakModeCharacterWrap].height;
                UILabel* cellText = [[UILabel alloc]initWithFrame:CGRectMake(36, 12, 200, tempHeight)];
                cellText.backgroundColor = [UIColor clearColor];
                cellText.numberOfLines = 0;
                cellText.text = [NSString stringWithFormat:@"地址：%@",placeDetailInfo.adress];
                [cell addSubview:cellText];
                [cellText release];
                
                UIImageView* towardImageView = [[UIImageView alloc] initWithFrame:CGRectMake(290-20, 14, 16, 21)];
                towardImageView.image = [UIImage imageNamed:@"icn_toward.png"];
                [cell addSubview:towardImageView];
                [towardImageView release];
            }
            else if (indexPath.row == 2)
            {
                UIImageView* phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 8, 34, 34)];
                phoneImageView.image = [UIImage imageNamed:@"icn_tel.png"];
                [cell addSubview:phoneImageView];
                [phoneImageView release];
                
                UILabel* cellText = [[UILabel alloc]initWithFrame:CGRectMake(36, 8, 200, 34)];
                cellText.backgroundColor = [UIColor clearColor];
                NSString* teleString;
                
                if (placeDetailInfo.telephone && ![placeDetailInfo.telephone isEqual:@""]) {
                    if ([placeDetailInfo.telephone rangeOfString:@" "].length > 0) {
                        teleString = [placeDetailInfo.telephone substringToIndex:[placeDetailInfo.telephone rangeOfString:@" "].location];
                    }
                    if ([placeDetailInfo.telephone rangeOfString:@","].length > 0) {
                        teleString = [placeDetailInfo.telephone substringToIndex:[placeDetailInfo.telephone rangeOfString:@","].location];
                    }
                    else {
                        teleString = placeDetailInfo.telephone;
                    }
                }
                else
                {
                    teleString = @"";
                }
                 
                cellText.text = [NSString stringWithFormat:@"电话：%@",teleString];
                cellText.numberOfLines = 1;
                [cell addSubview:cellText];
                [cellText release];
                
                UIImageView* towardImageView = [[UIImageView alloc] initWithFrame:CGRectMake(290-20, 14, 16, 21)];
                towardImageView.image = [UIImage imageNamed:@"icn_toward.png"];
                [cell addSubview:towardImageView];
                [towardImageView release];
            }
        }
            break;
        case 1:     
        {
            int tempHeight = [placeDetailInfo.review sizeWithFont:[UIFont systemFontOfSize:16.0f]
                                          constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:UILineBreakModeCharacterWrap].height;
            UILabel* cellText = [[UILabel alloc]initWithFrame:CGRectMake(10, 12, 280, tempHeight)];
            cellText.backgroundColor = [UIColor clearColor];
            cellText.numberOfLines = 0;
            cellText.font = [UIFont systemFontOfSize:16.0f];
            [cell addSubview:cellText];
            [cellText release];
            
            cellText.text = [NSString stringWithFormat:@"%@",placeDetailInfo.review];
        }
            break;
        case 2:
        {
            UILabel* cellText = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 280, 120)];
            cellText.backgroundColor = [UIColor clearColor];
            cellText.numberOfLines = 6;
            cellText.font = [UIFont systemFontOfSize:14.0f];
            [cell addSubview:cellText];
            [cellText release];
            
            cellText.text = @"无";
        }
            break;
            
        default:
            break;
    }
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //EventViewCell *cell = (EventViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //[cell selectButtonPressed];
    if (indexPath.section == 0 && indexPath.row == 1) {
        if (![placeDetailInfo.latitude isKindOfClass:[NSString class]] || [placeDetailInfo.latitude floatValue] == 0.0 || ![placeDetailInfo.langitude isKindOfClass:[NSString class]] || [placeDetailInfo.langitude floatValue] == 0.0) {
            baseAlert = [[UIAlertView alloc] initWithTitle:@"没有位置信息哟~" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [baseAlert show];
            return;
        }
        mapViewController *map = [[mapViewController alloc] initWithNibName:@"MapExample" bundle:nil];
        map.langitude = placeDetailInfo.langitude;
        map.latitude = placeDetailInfo.latitude;
        placeDetailInfo.cityid = [[DataSource shareInstance] getDefaultCityId];
        map.placeInfo = placeDetailInfo;
        map.isEdit = isEdit;
        [self.navigationController pushViewController:map animated:YES];
        [map release];    
    }
    else if (indexPath.section == 0 && indexPath.row == 2)
    {
        if (!placeDetailInfo.telephone || [placeDetailInfo.telephone isEqualToString:@""]) {
            baseAlert = [[UIAlertView alloc] initWithTitle:@"没有电话号码哟~" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [baseAlert show];
            return;
        }
        NSString *phoneNum;
        if ([placeDetailInfo.telephone rangeOfString:@" "].length > 0) {
            phoneNum = [placeDetailInfo.telephone substringToIndex:[placeDetailInfo.telephone rangeOfString:@" "].location];
        }
        else
        {
            phoneNum = placeDetailInfo.telephone;
        }
        
        NSString *urlPhoneNumber = [NSString stringWithFormat:@"tel://%@",[phoneNum stringByReplacingOccurrencesOfString:@"-" withString:@""]];
        
        
        NSLog(@"urlPhoneNumber : %@",phoneNum);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlPhoneNumber]];
        
//        NSString *phoneNum = placeDetailInfo.telephone;// 电话号码
//        
//        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]];
//        UIWebView* phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的容易 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
//        
//        [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
    }
    NSLog(@"index = %d",indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    //    self.tableView.delegate = nil;
    //    StatusCell *cell = (StatusCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //    self.tableView.delegate = self;
    //    return cell.cellHeight;
    NSInteger height = 0;
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    height = 100;
                    break;
                case 1:
                    height = [placeDetailInfo.adress sizeWithFont:[UIFont systemFontOfSize:18.0f]
                                                                 constrainedToSize:CGSizeMake(200, 9999) lineBreakMode:UILineBreakModeCharacterWrap].height+20;
                    if (height < 50) {
                        height = 50;
                    }
                    break;
                case 2:
                    height = 50;
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    int tempHeight = [placeDetailInfo.review sizeWithFont:[UIFont systemFontOfSize:16.0f]
                                     constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:UILineBreakModeCharacterWrap].height;
                    height = tempHeight+30;
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;    
        default:
            break;
    }
    
    return height;
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: SHOPDETAIL]) {
        self.placeDetailInfo = (PlaceDetailInfo*)data;
        [self.view addSubview:m_tableView];
        [m_tableView reloadData];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: ELEMENTSEARCH]) {
    }
}

@end
